package com.zz.cc.owner.app;

import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MKEvent;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.mapapi.map.RouteOverlay;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKPlanNode;
import com.baidu.mapapi.search.MKPoiInfo;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKShareUrlResult;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.zz.cc.owner.OwnerApplication;
import com.zz.cc.owner.R;
import com.zz.cc.owner.util.BMapUtil;
import com.zz.cc.owner.util.Util;

public class MapActivity extends OwnerBaseActivity {
	private MapView mMapView;
	private OwnerApplication mOwnerApplication;
	private LocationClient mLocClient;
	private MyLocationListener myLocationListener = new MyLocationListener();
	private MapController mMapController;
	private MKSearch mMkSearch;
	private MyOverlay mOverlay;
	private double myLatitude,myLongitude;
	private View viewCache = null;
	private View popupInfo = null;
	private View popupLeft = null;
	private View popupRight = null;
	private TextView popupText;
	private Button mPopButton;
	private PopupOverlay   pop  = null;
	private OverlayItem mCurItem = null;
	private MapView.LayoutParams layoutParam = null;
	private RouteOverlay routeOverlay = null;
	private Button mGoBackBtn;
	private MKSearchListener mkSearchListener = new MKSearchListener() {
		
		@Override
		public void onGetWalkingRouteResult(MKWalkingRouteResult arg0, int arg1) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onGetTransitRouteResult(MKTransitRouteResult arg0, int arg1) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onGetSuggestionResult(MKSuggestionResult arg0, int arg1) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onGetShareUrlResult(MKShareUrlResult arg0, int arg1, int arg2) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onGetPoiResult(MKPoiResult result, int type, int iError) {    
        	if ( iError == MKEvent.ERROR_RESULT_NOT_FOUND){  
        		mapMoveToPoint(myLatitude, myLongitude);
        		Toast.makeText(MapActivity.this, "抱歉，未找到结果",Toast.LENGTH_LONG).show();  
        	return ;  
        	        }  
        	        else if (iError != 0 || result == null) {  
        	        	mapMoveToPoint(myLatitude, myLongitude);
        	Toast.makeText(MapActivity.this, "搜索出错啦..", Toast.LENGTH_LONG).show();  
        	return;
        	        }
        	Util.showToast(MapActivity.this, "onGetPoiResult");
        	initOverlay(result.getAllPoi());
        	mMapView.getController().animateTo(new GeoPoint((int)(myLatitude*1E6), (int)(myLongitude*1E6)));    
        } 
		
		@Override
		public void onGetPoiDetailSearchResult(int arg0, int arg1) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onGetDrivingRouteResult(MKDrivingRouteResult res, int error) {
			// TODO Auto-generated method stub
			if (error == MKEvent.ERROR_ROUTE_ADDR){
				Util.showToast(MapActivity.this, "抱歉，搜索出现错误，请稍候重试");
				return;
			}
			if (error != 0 || res == null) {
				Toast.makeText(MapActivity.this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
				return;
			}
			routeOverlay = new RouteOverlay(MapActivity.this, mMapView);
		    // 此处仅展示一个方案作为示例
		    routeOverlay.setData(res.getPlan(0).getRoute(0));
		    //清除其他图层
		    mMapView.getOverlays().clear();
		    //添加路线图层
		    mMapView.getOverlays().add(routeOverlay);
		    //执行刷新使生效
		    mMapView.refresh();
		    // 使用zoomToSpan()绽放地图，使路线能完全显示在地图上
		    mMapView.getController().zoomToSpan(routeOverlay.getLatSpanE6(), routeOverlay.getLonSpanE6());
		    //移动地图到起点
		    mMapView.getController().animateTo(res.getStart().pt);
		    mGoBackBtn.setVisibility(View.VISIBLE);
		}
		
		@Override
		public void onGetBusDetailResult(MKBusLineResult arg0, int arg1) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onGetAddrResult(MKAddrInfo arg0, int arg1) {
			// TODO Auto-generated method stub
			
		}
	};
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		mOwnerApplication = (OwnerApplication)this.getApplication();
		mMkSearch = new MKSearch();
		mMkSearch.setPoiPageCapacity(50);
		mMkSearch.init(mOwnerApplication.mBMapManager, mkSearchListener);
		mOwnerApplication.mLocationClient.registerLocationListener(myLocationListener);
		mLocClient = mOwnerApplication.mLocationClient;
		mLocClient.registerLocationListener(myLocationListener);
		mMkSearch.init(mOwnerApplication.mBMapManager,mkSearchListener );
		initUI();
	}
	private void mapMoveToPoint(double latitude,double longitude){
		MyLocationOverlay myLocationOverlay = new MyLocationOverlay(mMapView);  
		LocationData locData = new LocationData();  
		//手动将位置源置为天安门，在实际应用中，请使用百度定位SDK获取位置信息，要在SDK中显示一个位置，需要使用百度经纬度坐标（bd09ll）  
		locData.latitude = latitude;  
		locData.longitude = longitude;  
		locData.direction = 2.0f;  
		myLocationOverlay.setData(locData);  
		mMapView.getOverlays().add(myLocationOverlay);  
		mMapView.refresh();  
		mMapView.getController().animateTo(new GeoPoint((int)(locData.latitude*1e6),  
		(int)(locData.longitude* 1e6)));  
	}
	private void initOverlay(List<MKPoiInfo> poiInfos){
		mOverlay.removeAll();
		for (MKPoiInfo mkPoiInfo : poiInfos) {
			OverlayItem item = new OverlayItem(mkPoiInfo.pt, mkPoiInfo.name, mkPoiInfo.phoneNum);
			item.setMarker(getResources().getDrawable(R.drawable.nav_turn_via_1));
			mOverlay.addItem(item);
		}
		
		OverlayItem myItem = new OverlayItem(new GeoPoint((int)(myLatitude*1E6), (int)(myLongitude*1E6)), "我的位置", "");
		myItem.setMarker(getResources().getDrawable(R.drawable.icon_geo));
		mOverlay.addItem(myItem);
		mMapView.getOverlays().add(mOverlay);
		mMapView.refresh();
		mMapView.getController().animateTo(myItem.getPoint()); 
		
		viewCache = getLayoutInflater().inflate(R.layout.custom_text_view, null);
        popupInfo = (View) viewCache.findViewById(R.id.popinfo);
        popupLeft = (View) viewCache.findViewById(R.id.popleft);
        popupRight = (View) viewCache.findViewById(R.id.popright);
        popupText =(TextView) viewCache.findViewById(R.id.textcache);
        mPopButton = new Button(this);
        mPopButton.setBackgroundResource(R.drawable.popup);
        PopupClickListener popListener = new PopupClickListener(){
			@Override
			public void onClickedPopup(int index) {
				if ( index == 0){
						searchDrivingDirection(mCurItem.getPoint());
				      mMapView.refresh();
				}
				else if(index == 2){
					//更新图标
					mCurItem.setMarker(getResources().getDrawable(R.drawable.nav_turn_via_1));
					mOverlay.updateItem(mCurItem);
				    mMapView.refresh();
				}
			}
         };
         pop = new PopupOverlay(mMapView,popListener);
	}
	private void initUI(){
		setContentView(R.layout.map);
		mGoBackBtn = (Button)findViewById(R.id.goback);
		mGoBackBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mMapView.getOverlays().clear();
				mMapView.refresh();
				requestLocation();
				mGoBackBtn.setVisibility(viewCache.GONE);
			}
		});
		((TextView)findViewById(R.id.titleTextView)).setText("地图模式");
		findViewById(R.id.backImg).setVisibility(View.GONE);
		((Button)findViewById(R.id.rightBtn)).setText("列表模式");
		((Button)findViewById(R.id.rightBtn)).setVisibility(View.VISIBLE);
		((Button)findViewById(R.id.rightBtn)).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent(MapActivity.this, StoreListActivity.class));
			}
		});
		mMapView = (MapView)findViewById(R.id.bmapsView);
		mMapView.setBuiltInZoomControls(true);  
		//设置启用内置的缩放控件  
		mMapController=mMapView.getController();  
		mOverlay = new MyOverlay(getResources().getDrawable(R.drawable.nav_turn_via_1), mMapView);
		// 得到mMapView的控制权,可以用它控制和驱动平移和缩放  
		GeoPoint point =new GeoPoint((int)(39.915* 1E6),(int)(116.404* 1E6));  
		//用给定的经纬度构造一个GeoPoint，单位是微度 (度 * 1E6)  
		mMapController.setCenter(point);//设置地图中心点  
		mMapController.setZoom(16);//设置地图zoom级别
		requestLocation();
	}
	private void searchDrivingDirection(GeoPoint endPoint){
		MKPlanNode startNode = new MKPlanNode();
		startNode.pt = new GeoPoint((int)(myLatitude*1E6), (int)(myLongitude*1E6));
		MKPlanNode endNode = new MKPlanNode();
		endNode.pt = endPoint;
		mMkSearch.setDrivingPolicy(MKSearch.ECAR_TIME_FIRST);
		mMkSearch.drivingSearch(null, startNode, null, endNode);
		
	}
	private void requestLocation(){
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);
		option.setAddrType("all");//返回的定位结果包含地址信息
		option.setCoorType("bd09ll");//返回的定位结果是百度经纬度,默认值gcj02
		option.setScanSpan(500);//设置发起定位请求的间隔时间为5000ms
		option.disableCache(true);//禁止启用缓存定位
		option.setPoiNumber(5);    //最多返回POI个数   
		option.setPoiDistance(1000); //poi查询距离        
		option.setPoiExtraInfo(true); //是否需要POI的电话和地址等详细信息
		mLocClient.setLocOption(option);
		mLocClient.start();
		mLocClient.requestLocation();
	}
	@Override
	public void onDestroy() {
		mMapView.destroy();
		super.onDestroy();
	}
	
	@Override
	public void onPause() {
		mMapView.onPause();
		super.onPause();
	}
	@Override
	public void onResume() {
		mMapView.onResume();
		super.onResume();
	}
	
	class MyLocationListener implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			
			if (location == null)
				return ;
			Util.showToast(MapActivity.this, "onReceiveLocation");
			myLatitude = location.getLatitude();
			myLongitude = location.getLongitude();
//			mMkSearch.poiSearchNearBy("车", new GeoPoint((int) (location.getLatitude() * 1E6), (int) (location.getLongitude() * 1E6)), 150000); 
			mMkSearch.poiSearchInCity(location.getCity(), "车");
		}
		
		public void onReceivePoi(BDLocation poiLocation) {
		}
	}
	
	
	class MyOverlay extends ItemizedOverlay{
		public MyOverlay(Drawable defaultMarker, MapView mapView) {
			super(defaultMarker, mapView);
		}
		@Override
		protected boolean onTap(int index) {
			OverlayItem item = getItem(index);
			mCurItem = item ;
			if (index == getAllItem().size()-1){
		         mPopButton.setText("我的当前位置");
		         GeoPoint pt = new GeoPoint ((int)(myLatitude*1E6),(int)(myLongitude*1E6));
		         //创建布局参数
		         layoutParam  = new MapView.LayoutParams(
		               //控件宽,继承自ViewGroup.LayoutParams
		               MapView.LayoutParams.WRAP_CONTENT,
		                //控件高,继承自ViewGroup.LayoutParams
		               MapView.LayoutParams.WRAP_CONTENT,
		               //使控件固定在某个地理位置
		                pt,
		                0,
		                -32,
		               //控件对齐方式
		                 MapView.LayoutParams.BOTTOM_CENTER);
		         //添加View到MapView中
		         mMapView.addView(mPopButton,layoutParam);
			}
			else{
			   popupText.setText(getItem(index).getTitle());
			   Bitmap[] bitMaps={
				    BMapUtil.getBitmapFromView(popupLeft), 		
				    BMapUtil.getBitmapFromView(popupInfo), 		
				    BMapUtil.getBitmapFromView(popupRight) 		
			    };
			    pop.showPopup(bitMaps,item.getPoint(),32);
			}
			return true;
		}
		@Override
		public boolean onTap(GeoPoint arg0, MapView arg1) {
			if (pop != null){
                pop.hidePop();
                mMapView.removeView(mPopButton);
			}
			return false;
		}
	}
}
